package com.peas.platform.module.icims.base.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peas.platform.common.core.configuration.RequestContextUtil;
import com.peas.platform.common.core.constant.Constants;
import com.peas.platform.common.core.property.ProjectProperties;
import com.peas.platform.framework.mybatisplus.domain.BaseDomain;
import com.peas.platform.framework.mybatisplus.po.BasePo;
import com.peas.platform.framework.mybatisplus.service.BaseServiceImpl;
import com.peas.platform.module.icims.base.sys.domain.SequenceDomain;
import com.peas.platform.module.icims.base.sys.dto.SequenceDto;
import com.peas.platform.module.icims.base.sys.service.SequenceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;

@Service
public class SequenceServiceImpl extends BaseServiceImpl<SequenceDto> implements SequenceService {

    @Resource
    private SequenceDomain sequenceDomain;
    @Resource
    private ProjectProperties projectProperties;

    @Override
    public BaseDomain<SequenceDto, ? extends BasePo> getDomain() {
        return sequenceDomain;
    }

    @Transactional
    @Override
    public String genSequence(String service, String model, String prefix, int bit, long startPos) {
        long sequence = 1;
        String no = prefix + String.format("%0" + bit + "d", sequence);
        OrderItem order = OrderItem.desc(Constants.DEFAULT_SORT_FIELD);
        Page<SequenceDto> pager = new Page<>();
        pager.setCurrent(1);
        pager.setSize(1);
        pager.setOrders(Collections.singletonList(order));
        SequenceDto c = new SequenceDto();
        c.setModel(model);
        c.setPrefix(prefix);
        Page<SequenceDto> page = this.page(pager, c);
        if (page != null && CollUtil.isNotEmpty(page.getRecords())) {
            sequence = page.getRecords().get(0).getSequenceIncrement();
            sequence++;
            no = prefix + String.format("%0" + bit + "d", sequence);
        }
        SequenceDto sd = new SequenceDto();
        sd.setSystem(projectProperties.getBusiness());
        sd.setSystemName(projectProperties.getBusinessName());
        sd.setService(projectProperties.getService());
        sd.setServiceName(projectProperties.getServiceName());
        sd.setModel(model);
        sd.setPrefix(prefix);
        sd.setSequenceNo(no);
        sd.setSequenceIncrement(sequence);
        sd.setSequenceTime(DateTime.now());
        sd.setSequenceUser(Long.valueOf(RequestContextUtil.getCurrentUserId(true)));
        this.save(sd);
        return no;
    }

}
